package com.vcit.system.service.clazz.impl;

import java.util.List;
import java.util.Arrays;
import java.util.stream.Collectors;

import com.vcit.common.core.domain.entity.TStudent;
import com.vcit.common.core.domain.model.LoginUser;
import com.vcit.common.utils.SecurityUtils;
import com.vcit.common.utils.bean.BeanUtils;
import com.vcit.common.utils.spring.SpringUtils;
import com.vcit.system.mapper.student.TStudentMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.vcit.common.utils.DateUtils;
import com.vcit.common.utils.StringUtils;
import com.vcit.system.domain.clazz.TClazzRule;
import com.vcit.system.domain.clazz.TClazzRuleMajor;
import com.vcit.system.domain.clazz.TClazzStudent;
import com.vcit.system.mapper.clazz.TClazzRuleMapper;
import com.vcit.system.mapper.clazz.TClazzRuleMajorMapper;
import com.vcit.system.mapper.clazz.TClazzStudentMapper;
import com.vcit.system.service.clazz.ITClazzRuleService;

/**
 * 分班规则Service业务层处理
 * 
 * @author vcit
 */
@Service
public class TClazzRuleServiceImpl implements ITClazzRuleService {
    @Autowired
    private TClazzRuleMapper tClazzRuleMapper;

    @Autowired
    private TClazzRuleMajorMapper tClazzRuleMajorMapper;

    @Autowired
    private TClazzStudentMapper tClazzStudentMapper;
    @Autowired
    TStudentMapper tStudentMapper;
    /**
     * 查询分班规则
     * 
     * @param id 分班规则主键
     * @return 分班规则
     */
    @Override
    public TClazzRule selectTClazzRuleById(Long id) {

       TClazzRule clazzRule = tClazzRuleMapper.selectTClazzRuleById(id);


        return clazzRuleStudentNum(clazzRule);
    }

    /**
     * 查询分班规则列表
     * 
     * @param tClazzRule 分班规则
     * @return 分班规则
     */
    @Override
    public List<TClazzRule> selectTClazzRuleList(TClazzRule tClazzRule) {
       List<TClazzRule>  clazzRuleList =  tClazzRuleMapper.selectTClazzRuleList(tClazzRule);

        return ruleStudentNum(clazzRuleList);
    }
    /**
     * 计算查询出的分班规则，包含专业的人数，计算出分班规则中的人数
     */
    public TClazzRule clazzRuleStudentNum(TClazzRule clazzRule){
        if(StringUtils.isEmpty(clazzRule.getMajorList())){
            return clazzRule;
        }
        int actual_count=0;// 实际人数
        int total_count=0;// 规定人数
        for (TClazzRuleMajor ruleMajor :clazzRule.getMajorList()){
            actual_count +=  ruleMajor.getActualCount();// 实际人数
            total_count+=ruleMajor.getStudentCount();// 规定人数
        }
        clazzRule.setActualCount(actual_count);
        clazzRule.setTotalCount(total_count);

        return clazzRule;
    }

    /**
     * 计算查询出的分班规则集合，便利规则，遍历包含专业的人数，计算出分班规则中的人数
     */
        public List<TClazzRule> ruleStudentNum(List<TClazzRule> clazzRuleList){
            if (StringUtils.isEmpty(clazzRuleList)) {
                return clazzRuleList;
            }

            for (TClazzRule clazzRule : clazzRuleList) {
                int actual_count=0;// 实际人数
                int total_count=0;// 规定人数
                for (TClazzRuleMajor ruleMajor :clazzRule.getMajorList()){
                    actual_count +=  ruleMajor.getActualCount();// 实际人数
                    total_count+=ruleMajor.getStudentCount();// 规定人数
                }
                clazzRule.setActualCount(actual_count);
                clazzRule.setTotalCount(total_count);

            }
            return clazzRuleList;
        }
    /**
     * 新增分班规则
     * 
     * @param tClazzRule 分班规则
     * @return 结果
     */
    @Transactional
    @Override
    public int insertTClazzRule(TClazzRule tClazzRule) {
        tClazzRule.setCreateTime(DateUtils.getNowDate());
        int rows = tClazzRuleMapper.insertTClazzRule(tClazzRule);
        insertTClazzRuleMajor(tClazzRule);// 分班规则 专业设置
        return rows;
    }

    /**
     * 修改分班规则
     * 
     * @param tClazzRule 分班规则
     * @return 结果
     */
    @Transactional
    @Override
    public int updateTClazzRule(TClazzRule tClazzRule) {
        tClazzRule.setUpdateTime(DateUtils.getNowDate());
        tClazzRuleMajorMapper.deleteTClazzRuleMajorByRuleId(tClazzRule.getId());//删除原先的
        insertTClazzRuleMajor(tClazzRule);// 分班规则 专业设置
        return tClazzRuleMapper.updateTClazzRule(tClazzRule);
    }

    /**
     * 批量删除分班规则
     * 
     * @param ids 需要删除的分班规则主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteTClazzRuleByIds(Long[] ids) {
        for (Long id : ids) {
            tClazzRuleMajorMapper.deleteTClazzRuleMajorByRuleId(id);
        }
        return tClazzRuleMapper.deleteTClazzRuleByIds(ids);
    }

    /**
     * 删除分班规则信息
     * 
     * @param id 分班规则主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteTClazzRuleById(Long id) {
        tClazzRuleMajorMapper.deleteTClazzRuleMajorByRuleId(id);
        return tClazzRuleMapper.deleteTClazzRuleById(id);
    }

    /**
     * 新增分班规则专业信息
     * 
     * @param tClazzRule 分班规则对象
     */
    public void insertTClazzRuleMajor(TClazzRule tClazzRule) {
        List<TClazzRuleMajor> majorList = tClazzRule.getMajorList();
        if (StringUtils.isNotEmpty(majorList)) {
            for (TClazzRuleMajor major : majorList) {
                major.setRuleId(tClazzRule.getId());
                major.setCreateTime(DateUtils.getNowDate());
                major.setCreateBy(tClazzRule.getCreateBy());
                tClazzRuleMajorMapper.insertTClazzRuleMajor(major);
            }
        }
    }

    /**
     * 执行分班规则
     * 
     * @param id 分班规则主键
     * @return 结果
     */
    @Transactional
    @Override
    public int executeClazzRule(Long id) {
        TClazzRule rule = tClazzRuleMapper.selectTClazzRuleById(id);
        if (rule == null) {
            throw new RuntimeException("分班规则不存在");
        }

        // 获取规则中的学生类型列表
        List<String> studentTypes = Arrays.asList(rule.getStudentTypes().split(","));
        
        // 遍历专业列表，为每个专业分配学生
        for (TClazzRuleMajor major : rule.getMajorList()) {
            // 查询符合条件的学生列表
            TClazzStudent query = new TClazzStudent();
            query.setMajorId(major.getMajorId());
            query.setZsYear(rule.getZsYear());
            query.setStudentType(rule.getStudentTypes());
            query.setClazzId(null); // 未分配班级的学生
            List<TClazzStudent> students = tClazzStudentMapper.selectTClazzEmptyStudentList(query);
            
            // 更新学生班级
            int count = 0;
            for (TClazzStudent student : students) {

                if (count >= major.getStudentCount()-major.getActualCount()) {
                    break;
                }
                student.setClazzId(rule.getClazzId());
                student.setUpdateTime(DateUtils.getNowDate());

                //更新学生在读状态
                TStudent stu = new TStudent();
                BeanUtils.copyProperties(student,stu);
                stu.setStatus(1);//在读
                stu.setZsStatus(8);//已分班
                stu.setId(student.getStudentId());
                stu.setUpdateTime(DateUtils.getNowDate());
                tStudentMapper.updateTStudent(stu);//更新学生状态
                student.setCreateTime(DateUtils.getNowDate());//班级分配时间
                student.setCreateBy(SecurityUtils.getUsername());
                tClazzStudentMapper.insertTClazzStudent(student);
                count++;
            }
            
            // 更新实际分配人数
            major.setActualCount(major.getActualCount()+count);
            tClazzRuleMajorMapper.updateTClazzRuleMajor(major);
        }
        
        // 更新规则状态为已执行
        rule.setStatus("1");
        return tClazzRuleMapper.updateTClazzRule(rule);
    }
} 